package org.bizon.dinner.common.gui;

import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JOptionPane;

import diiner.common.webaccess.DinnerService;
import diiner.common.webaccess.DinnerServiceService;
import diiner.common.webaccess.UnAutorizationException_Exception;
import org.bizon.dinner.common.interfaces.NB;

public class SecuritySystem {

	private static Long login = null;

	private static DinnerService service;

	public static DinnerService getDinnerService() {
		if (service == null) {
			service = new DinnerServiceService().getDinnerServicePort();
		}
		return service;
	}

	public static Long getID() {
		if (login == null) {
			login();
		}
		return login;
	}

	public static boolean isAdmin() {
		try {
			return service.getMenuList(login) != null;
		} catch (UnAutorizationException_Exception e) {
			return false;
		}
	}

	public static void login() {
		if (login == null) {
			LoginDialog dialog = new LoginDialog(NB.getINB().getMainWindow(), true);
			Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
			dialog.setLocation((dimension.width - dialog.getWidth()) / 2, (dimension.height - dialog.getHeight()) / 2);
			dialog.setVisible(true);
			String name = dialog.getUserName();
			String pass = dialog.getPass();
			try {
				login = getDinnerService().login(name, pass);
			} catch (UnAutorizationException_Exception e) {
				JOptionPane.showMessageDialog(NB.getINB().getMainWindow(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
			}
			if (login == null) {
				JOptionPane.showMessageDialog(null, "Wrong password");
				NB.getINB().exit(0);
			}
		}
	}

	public static void logout() {
		service.logout(login);
	}

	public static void showError(UnAutorizationException_Exception e) {
		JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
		NB.getINB().exit(0);
	}
}
